<template>
  <div class="couponym">
    <div class="mc_tk" v-if="mcflag">
      <mctk></mctk>
    </div>
    <a-tabs defaultActiveKey="2" @change="callback">
      <a-tab-pane tab="网络推广商销售统计" key="2" forceRender>
        <div class="top_fxtj">
          <div class="tit">销售业绩统计表</div>
          <div class="date">
            请选择
            <a-month-picker
              @change="ckdateChange"
              :defaultValue="moment(aData, monthFormat)"
              :format="monthFormat"
            />
          </div>
        </div>
        <div class="fxtj_box">
          <a-table
            :columns="fxtjcolumns"
            @change="getyhjjgl"
            :pagination="pagination"
            :dataSource="fxtjdata"
            bordered
          >
            <template
              v-for="col in ['sale_total', 'royalty_ratio', 'return_cash_total']"
              :slot="col"
              slot-scope="text, record, index"
            >
              <div class="rig_xse_bac" :key="col">{{text}}</div>
            </template>
            <template
              slot="agentProvice"
              slot-scope="text, record, index"
            >{{record.agentProvice}}{{record.agentCity}}{{record.agentDistrict}}</template>
            <template slot="mc" slot-scope="text, record, index">
              <div class="mc_box rig_xse_bac">
                <a-button @click="mxcick(record)" type="primary" size="small">明细</a-button>
              </div>
            </template>
            <template slot="cpfl" slot-scope="text, record, index">
              <div>
                <a-table :pagination='false' :columns="cpflcolumns" :data-source="record.sale_month_cp">
                  <!-- <a slot="name" slot-scope="text">{{ text }}</a> -->
                   <template slot="royalty_ratio" slot-scope="text, record, index">
              <div class="rig_xse_bac">{{text}}%</div>
            </template>
                </a-table>
              </div>
            </template>
            <template slot="royalty_ratio" slot-scope="text, record, index">
              <div class="rig_xse_bac">{{text}}%</div>
            </template>
          </a-table>
        </div>
      </a-tab-pane>

      <a-tab-pane tab="返现规则" key="1">
        <div class="fx_box">
          <div class="addyhj">
            <a-button type="primary" @click="showDrawer">添加规则</a-button>
          </div>
          <a-drawer
            title="添加规则"
            :width="720"
            @close="onClose"
            :visible="visible"
            :bodyStyle="{paddingBottom: '80px'}"
          >
            <a-form :form="form" layout="vertical" hideRequiredMark>
              <a-row :gutter="16">
                <a-col :span="20" class="colmar">
                  <span class="inp_tit">核算返利方式：</span>
                  <a-radio-group @change="xseradioChange" v-model="xsvalue">
                    <a-radio :style="radioStyle" :value="0">当月销售总额</a-radio>
                    <a-radio :style="radioStyle" :value="1">总销售额</a-radio>
                    <a-radio :style="radioStyle" :value="2">产品类型</a-radio>
                  </a-radio-group>
                </a-col>
                <a-col :span="12" class="colmar">
                  <a-form-item :label="xsvalue==2?'产品分类名称':'销售额'"></a-form-item>
                  <a-input-number
                    v-if="xsvalue!=2"
                    v-decorator="['sales_full', {
                  rules: [{ required: true, message: '请输提成比例' }]
                }]"
                    style="width:300px;"
                    id="inputNumber"
                    placeholder="请输入销售额"
                    :min="1"
                    :max="9999999"
                    v-model="sales_full"
                  />
                  <a-input v-if="xsvalue==2" placeholder="请输入包含关键字" v-model="sales_full" />
                </a-col>
                <a-col :span="12" class="colmar">
                  <a-form-item label="提成比例"></a-form-item>
                  <a-input-number
                    v-decorator="['royalty_ratio', {
                  rules: [{ required: true, message: '请输提成比例' }]
                }]"
                    style="width:300px;"
                    id="inputNumber"
                    placeholder="请输提成比例"
                    :min="1"
                    :max="100"
                    v-model="royalty_ratio"
                  />
                </a-col>
              </a-row>
            </a-form>
            <div
              :style="{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
                zIndex: 1,
               }"
            >
              <a-button :style="{marginRight: '8px'}" @click="onClose">取消</a-button>
              <a-button @click="addyhjsub" type="primary">提交</a-button>
            </div>
          </a-drawer>
          <a-table
            :columns="fxcolumns"
            @change="getfxgzlist"
            :dataSource="data"
            bordered
            :pagination="fxgzpagination"
          >
            <template slot="hsfs" slot-scope="text, record, index">
              <a-button v-if="record.type==0" size="small" type="primary">当月销售总额</a-button>
              <a-button v-if="record.type==1" size="small" type="danger">总销售额</a-button>
              <a-button v-if="record.type==2" size="small">产品类型</a-button>
            </template>
            <template
              v-for="startcol in ['sales_full']"
              :slot="startcol"
              slot-scope="text, record, index"
            >
              <div :key="startcol" v-if="record.type!=2">
                <span class="del" v-if="record.type!=2">≥</span>
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0;width:100px"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, startcol)"
                />
                <!-- <a-input-number
                  v-if="record.editable"
                  style="margin: -5px 0;width:100px"
                  :min="1"
                  :max="9999999"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, startcol)"
                />-->
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template
              v-for="productcol in ['product']"
              :slot="productcol"
              slot-scope="text, record, index"
            >
              <div :key="productcol" v-if="record.type==2">
                <!-- <span class="del" v-if="record.type!=2">≥</span> -->
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0;width:100px"
                  :value="text"
                  @change="e => prodChange(e.target.value, record.key, productcol)"
                />
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template
              v-for="endcol in ['royalty_ratio']"
              :slot="endcol"
              slot-scope="text, record, index"
            >
              <div :key="endcol">
                <div v-if="record.editable">
                  <a-input
                    style="margin: -5px 0;width:100px"
                    :value="text"
                    @change="e => handleChange(e.target.value, record.key, endcol)"
                  />
                  <span class="del">%</span>
                </div>

                <template v-else>
                  {{text}}
                  <span class="del">%</span>
                </template>
              </div>
            </template>

            <template slot="operation" slot-scope="text, record, index">
              <div class="editable-row-operations">
                <span v-show="record.editable">
                  <a class="del" @click="() => save(record,record.key)">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span class="del" v-show="!record.editable">
                  <a @click="() => edit(record.key)">修改</a>
                </span>
                <span class="del" v-show="!record.editable">
                  <a @click="deltel(record.key)">删除</a>
                </span>
              </div>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import qs from "qs";
import moment from "moment";
import mctk from "./mc_tk.vue";
const fxcolumns = [
  {
    title: "核算方式",
    dataIndex: "hsfs",
    scopedSlots: { customRender: "hsfs" }
  },
  {
    title: "销售额",
    dataIndex: "sales_full",
    scopedSlots: { customRender: "sales_full" }
  },
  {
    title: "产品分类",
    dataIndex: "product",
    scopedSlots: { customRender: "product" }
  },
  {
    title: "提成比例",
    dataIndex: "royalty_ratio",
    scopedSlots: { customRender: "royalty_ratio" }
  },

  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" }
  }
];
const cpflcolumns = [
  {
    title: "产品名称",
    dataIndex: "product",
    scopedSlots: { customRender: "product" }
  },
  {
    title: "当月销售额",
    dataIndex: "sale_month_cp",
    scopedSlots: { customRender: "sale_month_cp" }
  },
  {
    title: "返现比例",
    dataIndex: "royalty_ratio",
    scopedSlots: { customRender: "royalty_ratio" }
  },
  {
    title: "返现金额",
    dataIndex: "return_cash_month",
    scopedSlots: { customRender: "return_cash_month" }
  }
];
const fxtjcolumns = [
  {
    title: "编号",
    dataIndex: "id_num",
    scopedSlots: { customRender: "id_num" }
  },
  {
    title: "姓名",
    dataIndex: "username",
    scopedSlots: { customRender: "username" }
  },
  {
    title: "区域",
    dataIndex: "agentProvice",
    scopedSlots: { customRender: "agentProvice" }
  },
  {
    title: "当前核算方式",
    dataIndex: "checktype",
    scopedSlots: { customRender: "checktype" }
  },
    {
    title: "总销售额",
    dataIndex: "sale_total",
    scopedSlots: { customRender: "sale_total" }
  },
  {
    title: "当月业绩",
    dataIndex: "sale_month",
    scopedSlots: { customRender: "sale_month" }
  },
  {
    title: "当月返利",
    dataIndex: "return_cash_month",
    scopedSlots: { customRender: "return_cash_month" }
  },
   {
    title: "返现比例",
    dataIndex: "royalty_ratio",
    scopedSlots: { customRender: "royalty_ratio" }
  },
  {
    title: "产品分类",
    dataIndex: "cpfl",
    scopedSlots: { customRender: "cpfl" }
  },
  {
    title: "明细",
    dataIndex: "mc",
    scopedSlots: { customRender: "mc" }
  },


  // {
  //   title: "返现总额",
  //   dataIndex: "return_cash_total",
  //   scopedSlots: { customRender: "return_cash_total" }
  // }
  //   {
  //     title: "操作",
  //     dataIndex: "operation",
  //     scopedSlots: { customRender: "operation" }
  //   }
];

const data = [];
const fxtjdata = [];
export default {
  data() {
    this.cacheData = data.map(item => ({ ...item }));
    return {
      mcflag: false,
      moment,
      monthFormat: "YYYY-MM",
      aData: "",
      data,
      fxtjdata,
      fxtjcolumns,
      fxcolumns,
      cpflcolumns,
      editingKey: "",
      start_time: "",
      end_time: "",
      form: this.$form.createForm(this),
      visible: false,
      royalty_ratio: "", //添加提成比例
      sales_full: "", //添加销售额
      limit_times: "", //添加限领次数
      pagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      },
      fxgzpagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      },
      xsvalue: 0,
      radioStyle: {
        display: "inline-block",
        height: "30px",
        lineHeight: "30px"
      },
      mcval: ""
    };
  },

  methods: {
    showDrawer() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    callback(key) {
      console.log(key);
      if (key == 1) {
        this.getfxgzlist(this.fxgzpagination);
      } else {
        this.getyhjjgl(this.pagination);
      }
    },
    xseradioChange(e) {
      console.log("radio checked", e.target.value);
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    prodChange(value, key, column) {
      console.log(value);
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },

    mxcick(val) {
      this.mcval = val;
      console.log(val);
      this.mcflag = true;
    },
    deltel(key) {
      this.axios
        .post(
          "set/saleRoyaltyDelete.php",
          qs.stringify({
            id_num: key
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.getfxgzlist(this.fxgzpagination);
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },

    edit(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    startChange(date, dateString) {
      console.log(date, dateString);
      this.start_time = dateString;
    },
    endChange(date, dateString) {
      console.log(date, dateString);
      this.end_time = dateString;
    },
    save(value, key) {
      console.log(value);
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.key)[0];
      const targetCache = newCacheData.filter(item => key === item.key)[0];
      // target.editable = false;

      this.axios
        .post(
          "set/saleRoyaltyEdit.php",
          qs.stringify({
            id_num: value.id_num,
            type: value.type,
            sales_full:
              value.sales_full == null ? value.product : value.sales_full,
            royalty_ratio: value.royalty_ratio
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.getfxgzlist(this.fxgzpagination);
            if (target) {
              Object.assign(
                target,
                this.cacheData.filter(item => key === item.key)[0]
              );
              delete target.editable;
              this.data = newData;
            }
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter(item => key === item.key)[0]
        );
        delete target.editable;
        this.data = newData;
      }
    },
    getfxgzlist(pagination) {
      this.axios
        .post(
          "set/saleRoyaltyList.php",
          qs.stringify({
            page: pagination.current,
            pageSize: pagination.defaultPageSize,
            sqdwid: this.$store.state.bbl_sqdwid
          })
        )
        .then(res => {
          console.log("saleRoyaltyList+++++++", res);
          if (res.data.code == 303) {
            this.fxgzpagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            this.data = res.data.result.data;
            for (var i = 0; i < this.data.length; i++) {
              this.data[i].key = this.data[i].id_num;
            }
          }
        });
    },
    addyhjsub() {
      this.axios
        .post(
          "set/saleRoyaltyAdd.php",
          qs.stringify({
            sqdwid: this.$store.state.bbl_sqdwid,
            royalty_ratio: this.royalty_ratio,
            sales_full: this.sales_full,
            type: this.xsvalue
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.visible = false;
            this.getfxgzlist(this.fxgzpagination);
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    couponisOpen(value) {
      this.axios
        .post(
          "huiyuan/couponIsOpen.php",
          qs.stringify({
            id_num: value.id_num,
            is_open: value.is_open
          })
        )
        .then(res => {
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.getfxgzlist();
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    getyhjjgl(pagination, filed) {
      this.axios
        .post(
          "set/statisticsList.php",
          qs.stringify({
            page: pagination.current,
            pageSize: pagination.defaultPageSize,
            sqdwid: this.$store.state.bbl_sqdwid,
            filed: filed
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.pagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            this.fxtjdata = res.data.result.data;
            for (var i = 0; i < this.fxtjdata.length; i++) {
              this.fxtjdata[i].key = i;
              if (this.fxtjdata[i].checktype == "0") {
                this.fxtjdata[i].checktype = "当月销售总额";
              } else {
                this.fxtjdata[i].checktype = "总销售额";
              }
            }
          } else {
            this.fxtjdata = [];
          }
        });
    },
    ckdateChange(date, dateString) {
      console.log(date, dateString);
      this.getyhjjgl(this.pagination, dateString);
    },
    cplxChange(value) {
      console.log(`selected ${value}`);
    },
    handleBlur() {
      console.log("blur");
    },
    handleFocus() {
      console.log("focus");
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    }
  },
  components: {
    mctk
  },
  created() {
    this.getfxgzlist(this.fxgzpagination);
    this.getyhjjgl(this.pagination);
    // 获取当前时间
    var aData = new Date();
    this.aData = aData.getFullYear() + "-" + (aData.getMonth() + 1);
  }
};
</script>

<style lang='less'>
.couponym {
  width: 98%;
  margin: 0 auto;
  position: relative;
  top: 66px;
  text-align: left;
  background-color: #fff;
  padding: 15px;
}
.ant-form-item {
  margin: 0 !important;
}
.ant-form-item-label {
  padding: 0 !important;
}
.colmar {
  margin: 10px 0;
}
.fx_box {
  position: relative;
  .addyhj {
    position: absolute;
    top: -61px;
    right: 13px;
  }
}
.top_fxtj {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  align-items: center;
  .tit {
    font-size: 18px;
    font-weight: bold;
    padding: 0 10px;
  }
}
.fxtj_box {
  // thead {
  //   tr {
  //     th[key="sale_total"],
  //     th[key="royalty_ratio"],
  //     th[key="return_cash_total"],
  //     th[key="mc"] {
  //       padding: 0 !important;
  //       background: #40c7aebd;
  //       color: #fff;
  //     }
  //   }
  // }
  tbody {
    tr {
      td {
        padding: 0 !important;
        .rig_xse_bac {
          // background: #f7f7f7;
          padding: 10px 16px !important;
          color: #333;
          min-height: 41px;
        }
      }
    }
  }
}
.mc_tk {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 1000px;
  z-index: 999;
}
</style>
